import {
	token,
	TIMETAMP,
	codeTimestamp,
	userinfo,
	headName,
} from "./config.js"

import permision from "@/js_sdk/wa-permission/permission.js"

export function setToken(data) {
	uni.setStorageSync(token, data);
	setTimetamp()
}

export function getToken() {
	return uni.getStorageSync(token) || ""
}

export function removeToken() {
	uni.removeStorageSync(token);
	removeTimetamp()
	removeUserinfo()
}

export function setRefreshToken(data) {
	uni.setStorageSync("REFRESH-TOKEN", data);
}

export function getRefreshToken() {
	return uni.getStorageSync("REFRESH-TOKEN") || ""
}

export function removeRefreshToken() {
	uni.removeStorageSync("REFRESH-TOKEN");
}

export function setTimetamp(date) {
	let time = new Date().getTime()
	if (date) {
		time = getTime(date)
	}
	uni.setStorageSync(TIMETAMP, time);
}

export function getTimetamp() {
	return uni.getStorageSync(TIMETAMP) || ""
}

export function removeTimetamp() {
	uni.removeStorageSync(TIMETAMP);
}

export function setCodeTimetamp() {
	let time = new Date().getTime()
	uni.setStorageSync(codeTimestamp, time);
}

export function getCodeTimetamp() {
	return uni.getStorageSync(codeTimestamp) || ""
}

export function removeCodeTimetamp() {
	uni.removeStorageSync(codeTimestamp);
}

export function setUserinfo(data) {
	uni.setStorageSync(userinfo, data);
}

export function getUserinfo() {
	return uni.getStorageSync(userinfo) || {}
}

export function removeUserinfo() {
	uni.removeStorageSync(userinfo);
}

export function setChannel(data) {
	uni.setStorageSync("CHANNEL", data);
}

export function getChannel() {
	return uni.getStorageSync("CHANNEL") || {}
}

export function setAutoLogin(data) {
	uni.setStorageSync("AUTOLOGIN", data);
}

export function getAutoLogin() {
	return uni.getStorageSync("AUTOLOGIN") || false
}

export function setReceiptType(data) {
	uni.setStorageSync("RECEIPT", data);
}

export function getReceiptType() {
	return uni.getStorageSync("RECEIPT") || ""
}

export function setChargeIndex(data) {
	uni.setStorageSync("CHARGE-INDEX", data);
}

export function getChargeIndex() {
	return uni.getStorageSync("CHARGE-INDEX") || 0
}

export function removeChargeIndex() {
	uni.removeStorageSync("CHARGE-INDEX")
}

export function checkLoginAndVip(callback) {
	if (checkToken()) {
		if (checkVip()) {
			if (callback) {
				callback()
			}
		} else {
			let userinfo = getUserinfo()
			if (userinfo.vip && (userinfo.vip.code == 'ORDINARY' || userinfo.vip.code == 'TEMPORARY')) {
				callback(userinfo.vip.code)
			} else {
				showToast('您还不是会员,请先开通会员')
			}
		}
	} else {
		uni.showToast({
			icon: 'none',
			title: '您还未登录,请先登录',
			success() {
				setTimeout(() => {
					uni.navigateTo({
						animationType: 'pop-in',
						url: '/pages/login/login'
					})
				}, 1500)
			}
		})

	}
}

// export function checkToken() {
// 	let time = new Date().getTime()
// 	let backToken = getToken()
// 	let backTime = uni.getStorageSync(TIMETAMP)
// 	if (backToken) {
// 		if (backTime && time - backTime <= 23 * 60 * 60 * 1000) {
// 			return true;
// 		} else {
// 			removeUserinfo()
// 			removeToken()
// 			return false;
// 		}

// 	} else {
// 		removeUserinfo()
// 		removeToken()
// 		return false;
// 	}
// }

export function checkToken() {
	let backToken = getToken()
	if (backToken) {
		return true;
	} else {
		return false;
	}
}

export function checkVip() {
	let userinfo = getUserinfo()
	if (userinfo) {
		if (userinfo.remainDay > 0) {
			return true;
		}
	}
	return false;

}

export function checkAdminToken() {
	let time = new Date().getTime()
	let {
		check,
		expireTime,
		headName,
		token
	} = getPasswordCheck()
	if (check && token) {
		if (expireTime && time < expireTime) {
			return true;
		} else {
			removePasswordCheck()
			return false;
		}
	} else {
		removePasswordCheck()
		return false;
	}
}

export function checkCodeTimetamp() {
	let time = new Date().getTime()
	let backTime = getTimetamp()
	if (backTime) {
		if (time - backTime <= 7 * 60 * 60 * 1000) {
			// if (time - backTime <= 60* 1000) {
			return true;
		}
	}
	return false;
}
// 查询权限
export function getSetting(scope, text, block, errBlock = () => {}) {
	// #ifdef APP-PLUS
	if (uni.getSystemInfoSync().platform === "ios") {
		var result = permision.judgeIosPermission(scope)
		if (result) { // 由于 iOS 无法判断是第一次安装未授权过，还是拒绝了。所以先不用getSetting检查，直接调相册、通讯录等功能，等报错了再调getSetting
			block()
		} else {
			uni.showModal({
				content: text,
				confirmText: '去设置',
				cancelText: '取消',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						permision.gotoAppPermissionSetting()
					} else {
						errBlock(res)
					}
				},
			})
		}
	} else {
		permision.requestAndroidPermission(scope).then(result => {
			console.log("result", result)
			// result == 1  "已获得授权"
			//  result == 0 "未获得授权"
			if (result == 1) {
				block()
			} else if (result == 0) {
				errBlock(result)
			} else {
				uni.showModal({
					content: text,
					confirmText: '去设置',
					cancelText: '取消',
					showCancel: true,
					success: (res) => {
						if (res.confirm) {
							permision.gotoAppPermissionSetting()
						} else {
							errBlock(res)
						}
					},
				})
			}
		}).catch((e) => {
			console.log("requestAndroidPermission:error", e)
		})

	}

	// #endif
	// #ifdef MP
	uni.authorize({
		scope: scope,
		success: () => {
			console.log('已授权')
			block()
		},
		fail: () => {
			console.log('未授权')
			// 打开授权提示弹框
			uni.showModal({
				content: text,
				confirmText: '确认',
				cancelText: '取消',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						uni.openSetting({
							success: (data) => {
								if (data.authSetting[scope]) {
									block()
								} else {
									errBlock(data)
								}
							},
							fail(err) {
								errBlock(err)
							},
						})
					} else {
						errBlock(res)
					}
				},
			})
		},
	})
	// #endif
}

// // 自定义filter
// export function myFilter(value, options) {
// 	if (options && options instanceof Array) {
// 		let arr = options.filter(item => item.value === value)
// 		if (arr.length) {
// 			return arr[0] && arr[0].label
// 		} else {
// 			return value
// 		}
// 	} else {
// 		return value
// 	}
// }

// 自定义弹框消息
export function showToast(message, mask = false) {
	uni.showToast({
		title: message,
		icon: 'none',
		mask
	})
}



// 从path获取.后缀名 例如: .png
export function get_suffix(filename, noPoint) {
	let pos = filename.lastIndexOf('.');
	let suffix = '';
	if (pos != -1) {
		if (noPoint) {
			pos += 1
		}
		suffix = filename.substring(pos);
	}
	return suffix;
}

// 从base64文件中去后缀名
export function getSuffixname(base64) {
	if (base64) {
		let startIndex = base64.indexOf('/');
		if (startIndex >= 0) {
			let endIndex = base64.indexOf(';');
			if (endIndex >= 0) {
				let suffixName = base64.substring(startIndex + 1, endIndex);
				return suffixName;
			}
			return '';
		}
		return '';
	}
	return '';
}

// imageBase64转Blob
export function base64ToBlob(base64) {
	let arr = base64.split(',');
	let mime = arr[0].match(/:(.*?);/)[1];
	let bstr = atob(arr[1]);
	let n = bstr.length;
	let u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

// blob转file文件
export function blobToFile(blob, fileName) {
	blob.lastModifiedDate = new Date();
	blob.name = fileName;
	return blob;
}
// base64转file文件
export function base64toFile(dataurl, filename) { //将base64转换为文件
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {
		type: mime
	});
}

// 设置随机文件名 len
export function random_string(len = 32) {
	let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
	let maxPos = chars.length;
	let pwd = '';
	for (let i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

// 全局判断是否IOS方法
export function isIos() {
	const u = navigator.userAgent;
	return u.indexOf("iPhone") > -1 || u.indexOf("Mac OS") > -1;
}


// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

export const getTime = function(time) {
	var myDate = new Date(time);
	// var u = navigator.userAgent;
	// var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
	// var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
	let isiOS = uni.getSystemInfoSync().platform === "ios" ? true : false
	let t = ""
	if (isiOS) {
		if (typeof(time) === "string") {
			t = new Date(time.replace(/-/g, '/')).getTime();
		} else {
			t = myDate.getTime();
		}
	} else {
		t = myDate.getTime();
	}
	return t;
}


export function getAge(birthYearMonthDay) {
	//birthYearMonthDay必须为"1995/6/15"这种字符串格式，不可为"2020-6-15"，这种格式在Safari中会报错
	const birthDate = new Date(birthYearMonthDay);
	const momentDate = new Date();
	momentDate.setHours(0, 0, 0, 0); //因为new Date()出来的时间是当前的时分秒。我们需要把时分秒重置为0。使后面时间比较更精确
	const thisYearBirthDate = new Date(
		momentDate.getFullYear(),
		birthDate.getMonth(),
		birthDate.getDate()
	);
	const aDate = thisYearBirthDate - birthDate;
	const bDate = momentDate - birthDate;
	let tempAge = momentDate.getFullYear() - birthDate.getFullYear();
	let age = null;
	if (bDate < aDate) {
		tempAge = tempAge - 1;
		age = tempAge < 0 ? 0 : tempAge;
	} else {
		age = tempAge;
	}
	return age;
}



/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
	if (!source && typeof source !== 'object') {
		throw new Error('error arguments', 'deepClone')
	}
	const targetObj = source.constructor === Array ? [] : {}
	Object.keys(source).forEach(keys => {
		if (source[keys] && typeof source[keys] === 'object') {
			targetObj[keys] = deepClone(source[keys])
		} else {
			targetObj[keys] = source[keys]
		}
	})
	return targetObj
}

/**
 * 数字转财务数字
 * @param {String|Number} money
 * @returns {Object}
 */
export function keepTwoDecimalFull(num) {
	if (num == '' || num == null) {
		return "0.00";
	}
	var result = parseFloat(num);
	if (isNaN(result)) {
		console.log('传递参数错误，请检查！');
		return "0.00";
	}
	result = Math.round(num * 100) / 100;
	var s_x = result.toString(); //将数字转换为字符串

	var pos_decimal = s_x.indexOf('.'); //小数点的索引值


	// 当整数时，pos_decimal=-1 自动补0  
	if (pos_decimal < 0) {
		pos_decimal = s_x.length;
		s_x += '.';
	}

	// 当数字的长度< 小数点索引+2时，补0  
	while (s_x.length <= pos_decimal + 2) {
		s_x += '0';
	}
	return s_x;
}


/**
 * 获取星期几
 * 
 */
export function getWeek(date) {
	if (!date) {
		return ""
	}
	var tempDate = new Date(date);

	var days = tempDate.getDay();
	var week = '';

	switch (days) {
		case 1:
			week = '星期一';
			break;
		case 2:
			week = '星期二';
			break;
		case 3:
			week = '星期三';
			break;
		case 4:
			week = '星期四';
			break;
		case 5:
			week = '星期五';
			break;
		case 6:
			week = '星期六';
			break;
		case 0:
			week = '星期日';
			break;
	}
	return week
}

// 数字转为钱
export function formatCount(count) {
	var string = String(count || 0)
	if (!string) {
		return ''
	}
	var index = string.indexOf('.')
	if (index != -1) {
		string += '00'
		var num = 0
		if (Number(string.substring(index + 3, index + 4) || 0) >= 5) {
			num = 1
		}
		string = string.substring(0, index + 3)
		if (num > 0) {
			return formatCount(Math.round(Number(string) * 100 + num) / 100)
		}
	} else {
		string += '.00'
	}
	return string
}
// js将数字转换成万 并且保留两位小数
export function keepWFull(num) {
	let s_x = 0;
	// num=parseFloat(num)
	if (num > 10000) {
		let result = num / 10000;
		result = Math.floor(result * 100) / 100;
		s_x = result.toString(); //将数字转换为字符串
		let pos_decimal = s_x.indexOf("."); //小数点的索引值
		// 当整数时，pos_decimal=-1 自动补0
		if (pos_decimal < 0) {
			pos_decimal = s_x.length;
			s_x += ".";
		}
		// 当数字的长度< 小数点索引+2时，补0
		while (s_x.length <= pos_decimal + 2) {
			s_x += "0";
		}
		s_x += "万";
	} else {
		s_x = num.toString(); //将数字转换为字符串
		let pos_decimal = s_x.indexOf("."); //小数点的索引值
		if (pos_decimal != -1) {
			s_x = s_x.substring(0, pos_decimal + 3)
			s_x = s_x.replace(/(0+)$/g,'') // 去掉末尾的零
		}
	}
	return s_x;
}

export const convertCurrency = (money) => {
	//汉字的数字
	var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
	//基本单位
	var cnIntRadice = new Array('', '拾', '佰', '仟');
	//对应整数部分扩展单位
	var cnIntUnits = new Array('', '万', '亿', '兆');
	//对应小数部分单位
	var cnDecUnits = new Array('角', '分', '毫', '厘');
	//整数金额时后面跟的字符
	var cnInteger = '整';
	//整型完以后的单位
	var cnIntLast = '元';
	//最大处理的数字
	var maxNum = 999999999999999.9999;
	//金额整数部分
	var integerNum;
	//金额小数部分
	var decimalNum;
	//输出的中文金额字符串
	var chineseStr = '';
	//分离金额后用的数组，预定义
	var parts;
	if (money == '') {
		return '';
	}
	money = parseFloat(money);
	if (money >= maxNum) {
		//超出最大处理数字
		return '';
	}
	if (money == 0) {
		chineseStr = cnNums[0] + cnIntLast + cnInteger;
		return chineseStr;
	}
	//转换为字符串
	money = money.toString();
	if (money.indexOf('.') == -1) {
		integerNum = money;
		decimalNum = '';
	} else {
		parts = money.split('.');
		integerNum = parts[0];
		decimalNum = parts[1].substr(0, 4);
	}
	//获取整型部分转换
	if (parseInt(integerNum, 10) > 0) {
		var zeroCount = 0;
		var IntLen = integerNum.length;
		for (var i = 0; i < IntLen; i++) {
			var n = integerNum.substr(i, 1);
			var p = IntLen - i - 1;
			var q = p / 4;
			var m = p % 4;
			if (n == '0') {
				zeroCount++;
			} else {
				if (zeroCount > 0) {
					chineseStr += cnNums[0];
				}
				//归零
				zeroCount = 0;
				chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
			}
			if (m == 0 && zeroCount < 4) {
				chineseStr += cnIntUnits[q];
			}
		}
		chineseStr += cnIntLast;
	}
	//小数部分
	if (decimalNum != '') {
		var decLen = decimalNum.length;
		for (var i = 0; i < decLen; i++) {
			var n = decimalNum.substr(i, 1);
			if (n != '0') {
				chineseStr += cnNums[Number(n)] + cnDecUnits[i];
			}
		}
	}
	if (chineseStr == '') {
		chineseStr += cnNums[0] + cnIntLast + cnInteger;
	} else if (decimalNum == '') {
		chineseStr += cnInteger;
	}
	return chineseStr;
}


export function parseDuration(duration) {
	if(!duration){
		return "00:00:00"
	}
	let hour = parseInt((duration) / 3600);
	if (hour < 10) {
		hour = "0" + hour;
	}
	let minute = parseInt((duration % 3600) / 60);
	if (minute < 10) {
		minute = "0" + minute;
	}
	let second = Math.ceil(duration % 60);
	if (second < 10) {
		second = "0" + second;
	}
	let filetime = hour + ":" + minute + ":" + second;
	return filetime
}

export function parseDurationMinute(duration) {
	if(!duration){
		return "00:00"
	}
	let minute = parseInt(duration / 60);
	if (minute < 10) {
		minute = "0" + minute;
	}
	let second = Math.ceil(duration % 60);
	if (second < 10) {
		second = "0" + second;
	}
	let filetime =  minute + ":" + second;
	return filetime
}